/*
 * @Author: your name
 * @Date: 2022-02-04 10:26:22
 * @LastEditTime: 2022-02-05 13:25:19
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue3-vite-tsx\src\components\carousel-item\src\carousel-item.tsx
 */

import {
  defineComponent,
  getCurrentInstance,
  ComponentInternalInstance,
  ref,
  watch,
  Transition,
  
  VNode,
  RendererNode,
  RendererElement
} from 'vue'

import style from './carousel-item.module.less'

import './move.less'

interface Instance extends ComponentInternalInstance {
  vnode: VNode<RendererNode, RendererElement, { [key: string]: any }>
  ctx: { [key: string]: any }
  parent: Instance
}

export default defineComponent({
  name: 'CarouselItem',
  setup(props, ctx) {
    // 判断显示 当前索引，当前项目的索引
    const instance = getCurrentInstance() as unknown as Instance

    const itemIndex = instance.vnode.key

    const currentIndex = ref(0)
    instance.parent.ctx.currentIndex > -1
      ? (currentIndex.value = instance.parent.ctx.currentIndex)
      : 0

    watch(
      () => {
        return instance.parent.ctx.currentIndex
      },
      (newValue: number) => (currentIndex.value = newValue)
    )

    const direction = ref('next')

    watch(
      () => {
        return instance.parent.ctx.direction
      },
      (newValue) => (direction.value = newValue)
    )

    return {
      itemIndex,
      currentIndex,
      direction
    }
  },
  render() {
    const { default: defaultSlot } = this.$slots
    return (
      <>
        <Transition name={`move-${this.direction}`}>
          <div v-show={this.currentIndex == this.itemIndex} class={style['c-carousel-item']}>
            {this.direction}
            {defaultSlot && defaultSlot()}
          </div>
        </Transition>
      </>
    )
  }
})
